import datetime
import requests
from views import redis_tool
from views import notice_tool
from collections import Counter


UserID = '2429689'
CombID1 = '1461819'
CombID2 = '1464572'
RedCombID = '1503194'
YellowCombID = '1503195'


#获取开盘啦股票池的全部股票
def handle_kpl_table_stocks():
    params = {'PhoneOSNew': '2', 'Token': redis_tool.get_kpl_token(), 'UserID': UserID,
              'VerSion': '5.15.0', 'apiv': 'w37',
              'c': 'UserSelectStock', 'a': 'GetAllUserSelStock'}
    re = requests.get('https://applhb.longhuvip.com/w1/api/index.php', params=params)
    result = re.json()

    if result['errcode'] == '0':
        stock_dic = re.json()['StockList']
        return stock_dic
    else:
        return {}

# 删除开盘啦股票
def delete_kpl_stock(combid, stock_list):
    if len(stock_list) == 0:
        return
    params = {'CombineID': combid, 'DeviceID': '436b0b6010b384e985b1e54b0b2ae53ee51282bb',
              'PhoneOSNew': '2', 'StockID': ','.join(stock_list),
              'Token': redis_tool.get_kpl_token(), 'UserID': UserID,
              'VerSion': '5.15.0', 'apiv': 'w37',
              'c': 'UserSelectStock', 'a': 'DelStock'}
    re = requests.post('https://applhb.longhuvip.com/w1/api/index.php', params=params)
    print('删除信息：', re.json())

# 增加开盘啦股票
def add_kpl_table_stocks(combid, stock_list):
    if len(stock_list) == 0:
        return
    params = {'CombineID': combid, 'DeviceID': '436b0b6010b384e985b1e54b0b2ae53ee51282bb',
              'PhoneOSNew': '2', 'StockID': ','.join(stock_list),
              'Token': redis_tool.get_kpl_token(), 'UserID': UserID,
              'VerSion': '5.15.0', 'apiv': 'w37',
              'c': 'UserSelectStock', 'a': 'AddStockNew'}
    re = requests.post('https://applhb.longhuvip.com/w1/api/index.php', params=params)
    print('增加股票到kpl：', re.json())

#开盘啦增加股票通知
def add_kpl_stock_notify(code, NowCost30):
    params = { 'DeviceID': '436b0b6010b384e985b1e54b0b2ae53ee51282bb',
              'PhoneOSNew': '2', 'Token': redis_tool.get_kpl_token(), 'UserID': UserID,
              'VerSion': '5.15.0', 'apiv': 'w37', 'c': 'SingleStockNotify', 'a': 'ModStockNotify',
               'StockID': code,
               'DayFall': -1000, 'DayRise': -1000, 'Fall': NowCost30, 'Rise': -1000, 'FiveMinFall': -1000, 'FiveMinRise': -1000}
    re = requests.post('https://applhb.longhuvip.com/w1/api/index.php', params=params)

# 开盘啦添加笔记
def add_kpl_selected_stock_notes(code, note):
    notes = get_kpl_stock_notes(code)
    if len(notes) != 0:
        #清除笔记
        noteids = list(map(lambda x: f'{x["NoteID"]}', notes))
        stockids = list(map(lambda x: x['StockID'], notes))
        noteids_str = ','.join(noteids)
        stockids_str = ','.join(stockids)
        delete_kpl_stock_notes(noteids_str, stockids_str)

    url = 'https://apparticle.longhuvip.com/w1/api/index.php'
    params = {'NotesContent': note, 'StockID': code, 'c': 'UserNoteCommon', 'a': 'AddStockNotes', 'DeviceID': UserID,
              'PhoneOSNew': '2', 'Token': redis_tool.get_kpl_token(),  'UserID': UserID,
              'VerSion': '5.15.0', 'apiv': 'w37'}
    re = requests.post(url, params=params)
    result = re.json()
    if result['errcode'] == '0':
        print('添加股票笔记成功')
    else:
        print('添加股票笔记失败')

def add_kpl_candidate_stock_notes(code, note):
    notes = get_kpl_stock_notes(code)
    for no in notes:
        noteidstr = no["NoteID"]
        stockidstr = no["StockID"]
        note_str = no["NoteContent"]
        if '[精选]' not in note_str:
            delete_kpl_stock_notes(noteidstr, stockidstr)

    url = 'https://apparticle.longhuvip.com/w1/api/index.php'
    params = {'NotesContent': note, 'StockID': code, 'c': 'UserNoteCommon', 'a': 'AddStockNotes', 'DeviceID': UserID,
              'PhoneOSNew': '2', 'Token': redis_tool.get_kpl_token(),  'UserID': UserID,
              'VerSion': '5.15.0', 'apiv': 'w37'}
    re = requests.post(url, params=params)
    result = re.json()
    if result['errcode'] == '0':
        print('添加股票笔记成功')
    else:
        print('添加股票笔记失败')

# 获取笔记
def get_kpl_stock_notes(code):

    url = 'https://apparticle.longhuvip.com/w1/api/index.php'
    params = {'NoteIndex': 0, 'StockID': code, 'c': 'UserNoteCommon', 'a': 'GetStockNotes', 'DeviceID': UserID, 'PhoneOSNew': '2',
              'Token': redis_tool.get_kpl_token(), 'UserID': UserID,
              'VerSion': '5.15.0', 'apiv': 'w37', 'st': '20'}
    re = requests.post(url, params=params)
    result = re.json()
    print('股票笔记', re.json())
    if result['errcode'] == '0':
        return result['NotesList']
    return list()

def delete_kpl_stock_notes(noteIDs, stockIDs):

    url = 'https://apparticle.longhuvip.com/w1/api/index.php'
    params = {'NoteID': noteIDs, 'StockID': stockIDs, 'c': 'UserNoteCommon', 'a': 'DelNotes', 'DeviceID': UserID, 'PhoneOSNew': '2',
              'Token': redis_tool.get_kpl_token(), 'PhoneOSNew': '2', 'UserID': UserID,
              'VerSion': '5.15.0', 'apiv': 'w37'}
    re = requests.post(url, params=params)
    result = re.json()
    if result['errcode'] != '0':
        notice_tool.send_push_message('删除股票笔记失败')

#获取开盘了股票概念信息
def get_kpl_hots(code):
    url = 'https://apphwhq.longhuvip.com/w1/api/index.php?'
    params = {'StockID': code, 'c': 'StockL2Data', 'a': 'GetFeaturedSection',
              'PhoneOSNew': '2',
              'VerSion': '5.15.0', 'apiv': 'w37'}
    re = requests.post(url, params=params)
    result = re.json()
    if result['errcode'] == '0':
        return result['info']
    else:
        notice_tool.send_push_message('获取开盘了股票概念信息失败')
        return list()

#获取历史数据
def get_kpl_his_data(code):
    # open   close  hight  low
    # [21.3, 20.77, 21.71, 20.65]
    url = 'https://apphis.longhuvip.com/w1/api/index.php'
    params = {'StockID': code, 'c': 'StockLineData', 'a': 'GetKLineDay_W14',
              'PhoneOSNew': '2',
              'VerSion': '5.16.0.5', 'apiv': 'w37', 'st': '6', 'Index': '0', 'Type': 'd'}
    re = requests.post(url, params=params)
    result = re.json()
    return result
def get_kpl_real_data(code):
    url = 'https://apphwhq.longhuvip.com/w1/api/index.php'
    params = {'StockID': code, 'c': 'StockL2Data', 'a': 'GetStockPanKou_Narrow',
              'PhoneOSNew': '2',
              'VerSion': '5.16.0.5', 'apiv': 'w38', 'State': '1'}
    re = requests.post(url, params=params)
    result = re.json()
    return result

def get_low_data(code):
    low = 10000
    last_px = 0
    his_data = get_kpl_his_data(code)
    if his_data['errcode'] != '0':
        return low, last_px
    else:
        dates = his_data['x']
        last_px = his_data['y'][len(dates) - 1][1]
        for i in reversed(range(len(dates))):
            if i == 0:
                break
            pre_close = his_data['y'][i-1][1]
            rate = (his_data['y'][i][1] - pre_close) / pre_close * 100
            if rate > 9.5:
                if low > his_data['y'][i][1]:
                    low = his_data['y'][i][1]
                break
            if low > his_data['y'][i][3]:
                low = his_data['y'][i][3]
        return low, last_px

def get_defensive_data(code):
    defensive = 0
    last_px = 0
    his_data = get_kpl_his_data(code)
    if his_data['errcode'] != '0':
        return defensive, last_px
    else:
        dates = his_data['x']
        last_px = his_data['y'][len(dates) - 1][1]
        for i in reversed(range(len(dates))):
            if i == 0:
                break
            pre_close = his_data['y'][i-1][1]
            rate = (his_data['y'][i][1] - pre_close) / pre_close * 100
            if rate > 9.5:
                defensive = his_data['y'][i][3]
                break
        return defensive, last_px

# 获取最近八天股票概念排行榜
def gethots(dates):
    date_array = dates.split(',')
    hots = []
    for date in date_array:
        url = 'https://apphis.longhuvip.com/w1/api/index.php'
        params = {'Date': date, 'Index': '0', 'Order': '1',
                  'PhoneOSNew': '2', 'Type': '1',
                  'VerSion': '5.17.0.9', 'ZSType': '7', 'a': 'RealRankingInfo',
                  'apiv': 'w38', 'c': 'ZhiShuRanking', 'st': 8}
        re = requests.post(url, params=params)
        result = re.json()
        if result['errcode'] == '0':
            subHots = list(map(lambda x: x[1], result['list']))
            hots.extend(subHots)
        else:
            return []
    counter = Counter(hots)
    sorted_counts = counter.most_common()
    res = [item for item, count in sorted_counts]
    return res